<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\Dashboard;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;

use Encore\Admin\Grid;
use Encore\Admin\Form;
use App\Models\EMail;


use App\Admin\Extra\Search\Html;
use \Illuminate\Support\Facades\Input;

use App\Models\Area;
use Redirect;
class MailController extends Controller
{
    public function index()
    {

        $use_data['area_all'] = Area::areaSelectData(0);
        $use_data['area_online'] = Area::areaSelectData();
        \Log::debug('mail index', [$use_data]);
        return Admin::content(function (Content $content)use($use_data) {
            $content->header('email list');
            $content->row(Html::append([
                Html::likeRedirect('title', 'email title', url()->current()),
                Html::button('GO', url()->current(), 'search-filter'),
                Html::sjs(url()->current()),
            ]));	

			$grid = Admin::grid(EMail::class, function(Grid $grid) use($use_data){
                $grid->model()->where('deleted_at', 0);

                $grid->actions(function($actions)use(&$row){
                    $row = $actions->row;
                    $actions->disableEdit();
                    $actions->disableDelete();
                    $actions->append(Html::button('EDIT', '/admin/mail/edit?id='.$actions->getKey(), 'btn-goto btn-xs'));
                    $actions->append(Html::button('CLONE', '/admin/mail/edit?id='.$actions->getKey().'&clone=1', 'btn-goto btn-xs'));
                    $actions->append(Html::button('DEL', '/admin/mail/api-save?_id='.$actions->getKey().'&deleted_at=1', 'btn-goto btn-danger btn-xs btn-clear'));
                });

			    // 第一列显示id字段，并将这一列设置为可排序列
			    $grid->id('ID')->sortable();
                $grid->model()->orderBy('id', 'DESC');
                $grid->title('title')->limit(20);
                $grid->receive_method('receive_method')->display(function($value){
                    return '<fount>'.EMail::$send_mail_type[$value].'</fount>' ?: $value;
                });
                $grid->area_list('area')->display(function($value)use($use_data){
                    return $use_data['area_all'][$value] ?: $value;
                });

                $grid->add_time('create time')->display(function($value){
                    if (is_numeric($value)) {
                        $value = date("Y-m-d H:i:s", $value);
                    }
                    return $value;
                });
                $grid->end_time('end time')->display(function($value){
                    if (is_numeric($value)) {
                        $value = date("Y-m-d H:i:s", $value);
                    }
                    return $value?:'';
                });

                $grid->send_time("send status")->display(function($value){
                    if ($value > 0) {
                        return date("Y-m-d H:i:s",$value);
                    }
                    // 群发
                    if ($this->receive_method == 3 || $this->receive_method == 4) {
                        return Html::button('send', '/admin/mail/api-send?id='.$this->id.'&status='.'1', 'confirm-ajax btn-xs btn-danger');
                    }
                    return Html::button('send', '/admin/mail/api-send?id='.$this->id.'&status='.'1', 'btn-goto-ajax btn-xs btn-info');
                });
                // 服务当前状态
                // $states = [
                //     'on'  => ['value' => 0, 'text' => '发送', 'color' => 'success'],
                //     'off' => ['value' => 1, 'text' => 'over', 'color' => 'default'],
                //     'url' => url()->to("/admin/mail/api-send?_id={$row->id}"),
                // ];

                
                // // 设置临时跳转路径 行操作使用 TODO
                // //$grid->tmpUrl = url()->to("/admin/game-db-conf/api-save?id=".$grid->getKey()->value()."&status=".(''?0:1));
                // $tmp = $grid->send_time('send status')->switch($states)->display(function($value){
                //     $this->tmpUrl = url()->to("/admin/mail/api-send?_id=".$this->id."&status=".($value?0:1));
                //     return $value;
                // });

			    $grid->filter(function ($filter) use($use_data) {

                    // 模糊查询 注意
			        //$filter->where(function($query){
                    //    //$aids = \App\Models\EMail::getAccountByName('', 'playerName');
                    //    //var_dump($aids);exit;
                    //    $query->where('title', 'like', 'T%');
                    //}, '邮件标题', 'title');

                    $filter->like('title', 'mail title')->placeholder('');
                    $filter->equal('area_list')->select($use_data['area_online']);
                    $filter->equal('send_time')->placeholder('is send mail');

                    //$filter->disableIdFilter();
			    });

            });
        
            $content->row($grid->render());

        });
    }

    public function anyEdit(){
        $id = Input::get('id');
        $clone = Input::get('clone');

        $one = EMail::find($id) ?: new EMail;
        if (!$one->id){
            $one->receive_method = 1;
            // 此处直接接收json串
            $receiver = Input::get('receiver');
            if ((string)intval($receiver) == $receiver){
                $receiver = '['.$receiver.']';
            }
            $one->receiver = $receiver;
            $one->area_list = Input::get('area');
        }
        $data['one'] = $one;
        $data['clone'] = $clone;

        \Log::debug("edit email",[Area::areaSelectData(), intval($one->area_list)]);
        return Admin::content(function($content) use($data){
		    $content->header('邮件编辑');
            $grid = Admin::Form(EMail::class, function(Form $form)use($data){
                $one = $data['one'];
                //$one->area_list = explode(',', $one->area_list);

                $form->text('title', 'title')->default($one->title);
                $form->textarea('content', 'content')->default($one->content);
                $form->select('receive_method', 'receive method')->options(EMail::$send_mail_type)->default($one->receive_method);
                $form->text('receiver', 'receiver')->default($one->receiver);
                $form->select('area_list', 'area')->options(Area::areaSelectData())->default($one->area_list);
                $form->text('gold', 'gold')->default($one->gold ?: '0');
                $form->text('diamond', 'diamond')->default($one->diamond ?: '0');
                $form->text('ticket', 'ticket')->default($one->ticket ?: '0');
                $form->datetime('end_time', 'expire time')->default($one->end_time);
                //$form->textarea('prop', 'attach')->default($one->prop);
                $form->html(\App\Admin\Extra\Form\TForm::mutilSelectItem('prop', $one->prop, 'attach', '/admin/mail/item-all'), 'attach');
        
                if (!$data['clone']) {
                    $form->hidden('_id', 'id')->default($one->id);
                }

                $form->saved(function (Form $form) {
                    \Log::debug(json_encode(['data'=>'save click']));
                    admin_toastr('laravel-admin 提示','success');
                    return response('success');
                });

                $form->disablePjax();
                $form->setAction('/admin/mail/api-save/');

            });
            $content->row($grid);
        });

    }

    public function anyAdd()
    {
        return $this->anyEdit();
    }

    public function anyApiSave(){
        $data = Input::all();

        $url = url()->to("/admin/mail/index");
        \Log::debug(json_encode(['data'=>$data, 'url' =>$url]));
        $one = EMail::find($data['_id']) ? : new EMail();

        EMail::assignByOut($one, $data);
        
        if (!$one->title || !$one->content) {
            echo json_encode(['code' => 444, 'msg' => admin_toastr('email save param!','error'), 'data' => $data]);
            return;
        }
        // 如果给某个人发，选择了群发则将群发类型设置成单发类型
        if (intval($one->receiver) > 0 && $one->receive_method >= 3 ) {
            $one->receive_method = 1;
        }
        $one->save();
        
        echo json_encode(['code' => 0,'status'=>true, 'msg' => admin_toastr('email save!','success'), 'data' =>$one->delete_at]);
        return;
    }

    public function anyApiSend(){
        $data = Input::all();
        $id = $data["_id"] ?: $data["id"];
        $status = $data["status"] ?: 0;
        $one = EMail::find($id) ? : new EMail();

        \Log::debug('send mail begin', [json_encode($one)]);
        if (!$status || !$id || !$one->id){
            admin_toastr('send email error!','error');
            //return redirect('/admin/mail/?code=0&redirect='.url()->to('/admin/mail/').'');
            echo json_encode(['code' => -444,'status'=>true, 'msg' => admin_toastr('send email error','error'), 'data' =>$one->delete_at]);
            return;
        }

        $one->send_time = time();
        $one->save();
        \Log::debug("send mail over", [$one]);
        // 发送邮件
        EMail::send($one);
        echo json_encode(['code' => 0,'status'=>true, 'msg' => admin_toastr('send email success','success'), 'data' =>$one->delete_at]);
    }

    // item all 
    public function anyItemAll()
    {
        $item_obj = new \App\Models\Item\Item();
        $result['code'] = 0;
        $result["data"] = $item_obj->GetItemArray(Input::get('offset', 0));
        $result['count'] = $item_obj->GetItemCount();
        echo json_encode($result);
        
    }
}
